package com.qianfeng.zhangwei.day43.widget;

import android.content.Context;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.qianfeng.zhangwei.day43.R;

import java.lang.reflect.Field;

/**
 * @说 明：
 * @项目名称：1506adc
 * @包 名： com.qianfeng.zhangwei.day39
 * @类 名：FloatView
 * @创 建人：zhangwei
 * @创建时间：2015-07-01 15 : 54
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class FloatView extends ImageView {
    private WindowManager wm;
    WindowManager.LayoutParams params;

    /**
     * @param context
     */
    public FloatView(Context context) {
        super(context);
        init();
    }

    private void init() {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        setLayoutParams(params);
        setBackgroundResource(R.mipmap.ic_launcher);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int height = getHeight() / 2;
        int width = getWidth() / 2;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                update(event.getRawX() - width, event.getRawY() - getstateBar() - height);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.onTouchEvent(event);
    }

    private void update(float x, float y) {
        params.x = (int) x;
        params.y = (int) y;
        wm.updateViewLayout(this, params);
    }


    public void setParams(WindowManager.LayoutParams params) {
        this.params = params;
    }

    public void setWm(WindowManager wm) {
        this.wm = wm;
    }


    /**
     * 获取状态栏的高度
     *
     * @return
     */
    private int getstateBar() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");

            obj = c.newInstance();

            field = c.getField("status_bar_height");

            x = Integer.parseInt(field.get(obj).toString());

            sbar = getResources().getDimensionPixelSize(x);

        } catch (Exception e1) {
            e1.printStackTrace();

        }
        return sbar;


    }
}
